package com.wzdigit.wms.wms.service.basic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.SkuAttr;
import com.wzdigit.wms.basic.domain.basic.SkuCate;
import com.wzdigit.wms.basic.domain.basic.SkuCtrl;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.request.basic.*;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.client.response.basic.*;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.basic.mapper.core.basic.SkuAttrMapper;
import com.wzdigit.wms.basic.mapper.core.basic.SkuCateMapper;
import com.wzdigit.wms.basic.mapper.core.basic.SkuCtrlMapper;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 货品服务类
 * @author yangdongjie
 * @UserDataPermissionService.java
 * @2021年1月18日下午4:02:50
 */
@Service
public class SkuService {

	@Autowired
    private SkuMapper skuMapper;
	
	@Autowired
    private SkuCateMapper skuCateMapper;
	
	@Autowired
    private SkuAttrMapper skuAttrMapper;
	
	@Autowired
    private SkuCtrlMapper skuCtrlMapper;
	
	
	@SuppressWarnings("rawtypes")
	public PagerInfo<List<SkuBaseResponse>> searchSku(SearchSkuRequest dto) {
    	Page page = PageHelper.offsetPage(dto.getSkipCount(), dto.getMaxResultCount());
        PagerInfo<List<SkuBaseResponse>> pagerInfo = new PagerInfo<List<SkuBaseResponse>>();
        List<SkuBaseResponse> list = skuMapper.selectAll(dto);
        pagerInfo.setItems(list);
        pagerInfo.setTotalCount(page.getTotal());
		return pagerInfo;
    }
	
	public SkuResponse getSku(Integer skuId) {
		SkuResponse response = new SkuResponse();
		
		// 货品基本信息
		SkuBaseResponse skuBaseResponse = skuMapper.selectOneBySkuId(skuId);
    	BeanUtil.copyNonNull(skuBaseResponse, response);
    	
    	// 货品类别信息
    	SkuCate skuCate = skuCateMapper.selectById(skuBaseResponse.getSkuCateId());
		SkuCateResponse skuCateResponse = new SkuCateResponse();
    	BeanUtil.copyNonNull(skuCate, skuCateResponse);
    	response.setCate(skuCateResponse);
    	
    	// 货品控制信息
    	SkuCtrlResponse ctrlResponse = skuCtrlMapper.selectOneBySkuId(skuId);
    	if(ctrlResponse != null) {
    		Date date = ctrlResponse.getValidDateFrom();
    		if(date != null) {
    			ctrlResponse.setValidTimeFrom(date.getTime());
    		}
    		date = ctrlResponse.getValidDateTo();
    		if(date != null) {
    			ctrlResponse.setValidTimeTo(date.getTime());
    		}
    	}
    	response.setCtrl(ctrlResponse);
    	
    	// 货品属性
    	response.setAttrs(skuAttrMapper.selectAllBySkuId(skuId));
		return response;
    }
	
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public SkuResponse createSku(CreateSkuRequest dto,
    		HttpServletRequest servletRequest) {
		String loginName = HttpSessionUtil.getLoginName(servletRequest);
		
		QueryWrapper<Sku> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("SKU_CODE", dto.getSkuCode());
		Sku sku = skuMapper.selectOne(queryWrapper);
		if (sku != null) {
			// 编码已存在
    		Shift.fatal(StatusCode.CODE_DATA_EXIST);
		}
		
		Date date = new Date();
		// 货品基本信息
		sku = new Sku();
    	BeanUtil.copyNonNull(dto, sku);
    	sku.setCreateUser(loginName);
    	sku.setCreateTime(date);
    	skuMapper.insert(sku);
    	
    	SkuResponse response = new SkuResponse();
    	BeanUtil.copyNonNull(sku, response);
    	
    	// 货品控制信息
    	CreateUpdateSkuCtrlRequest ctrl = dto.getCtrl();
		if (ctrl != null) {
			SkuCtrlResponse ctrlResponse = new SkuCtrlResponse();
			
			SkuCtrl skuCtrl = new SkuCtrl();
			BeanUtil.copyNonNull(ctrl, skuCtrl);
			skuCtrl.setSkuId(sku.getSkuId());
			skuCtrl.setCreateUser(loginName);
			skuCtrl.setCreateTime(date);
			if(ctrl.getValidDateFrom() != null){
				ctrlResponse.setValidTimeFrom(ctrl.getValidDateFrom());
				skuCtrl.setValidDateFrom(new Date(ctrl.getValidDateFrom()));
			}
			if(ctrl.getValidDateTo() != null){
				ctrlResponse.setValidTimeTo(ctrl.getValidDateTo());
				skuCtrl.setValidDateTo(new Date(ctrl.getValidDateTo()));
			}
			skuCtrlMapper.insert(skuCtrl);
			
			BeanUtil.copyNonNull(skuCtrl, ctrlResponse);
			
			response.setCtrl(ctrlResponse);
		}
    	
    	// 货品属性
		if (dto.getAttrs() != null) {
			SkuAttr skuAttr = null;
			List<SkuAttrResponse> attrs = new ArrayList<SkuAttrResponse>(dto.getAttrs().size());
			for (CreateUpdateSkuAttrRequest attr : dto.getAttrs()) {
				skuAttr = new SkuAttr();
				BeanUtil.copyNonNull(attr, skuAttr);
				skuAttr.setSkuId(sku.getSkuId());
				skuAttr.setCreateUser(loginName);
				skuAttr.setCreateTime(date);
				skuAttrMapper.insert(skuAttr);
				
				SkuAttrResponse skuAttrResponse = new SkuAttrResponse();
				BeanUtil.copyNonNull(skuAttr, skuAttrResponse);
				attrs.add(skuAttrResponse);
			}
			response.setAttrs(attrs);
		}
		return response;
    }
    
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public SkuResponse updateSku(UpdateSkuRequest dto,
    		HttpServletRequest servletRequest) {
		String loginName = HttpSessionUtil.getLoginName(servletRequest);
		
		QueryWrapper<Sku> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("SKU_CODE", dto.getSkuCode());
		Sku sku = skuMapper.selectOne(queryWrapper);
		if (sku != null) {
			// 编码已存在
			if(sku.getSkuId().intValue() != dto.getSkuId().intValue()){
				Shift.fatal(StatusCode.CODE_DATA_EXIST);
			}
		}
		
		Date date = new Date();
		
		// 货品基本信息
		sku = skuMapper.selectById(sku.getSkuId());
    	BeanUtil.copy(dto, sku);
    	sku.setModifyUser(loginName);
    	sku.setModifyTime(date);
    	skuMapper.updateById(sku);
    	
    	SkuResponse response = new SkuResponse();
    	BeanUtil.copyNonNull(sku, response);
    	
    	// 货品控制信息
    	CreateUpdateSkuCtrlRequest ctrl = dto.getCtrl();
		if (ctrl != null) {
			SkuCtrlResponse ctrlResponse = new SkuCtrlResponse();
			
			QueryWrapper<SkuCtrl> skuCtrlQueryWrapper = new QueryWrapper<>();
			skuCtrlQueryWrapper.eq("SKU_ID", dto.getSkuId());
			SkuCtrl skuCtrl = skuCtrlMapper.selectOne(skuCtrlQueryWrapper);
			if(skuCtrl == null){
				skuCtrl = new SkuCtrl();
				BeanUtil.copyNonNull(ctrl, skuCtrl);
				if(ctrl.getValidDateFrom() != null){
					ctrlResponse.setValidTimeFrom(ctrl.getValidDateFrom());
					skuCtrl.setValidDateFrom(new Date(ctrl.getValidDateFrom()));
				}
				if(ctrl.getValidDateTo() != null){
					ctrlResponse.setValidTimeTo(ctrl.getValidDateTo());
					skuCtrl.setValidDateTo(new Date(ctrl.getValidDateTo()));
				}
				skuCtrl.setSkuId(sku.getSkuId());
				skuCtrl.setCreateUser(loginName);
				skuCtrl.setCreateTime(date);
				skuCtrlMapper.insert(skuCtrl);
			} else {
				BeanUtil.copy(ctrl, skuCtrl);
				if(ctrl.getValidDateFrom() != null){
					ctrlResponse.setValidTimeFrom(ctrl.getValidDateFrom());
					skuCtrl.setValidDateFrom(new Date(ctrl.getValidDateFrom()));
				}
				if(ctrl.getValidDateTo() != null){
					ctrlResponse.setValidTimeTo(ctrl.getValidDateTo());
					skuCtrl.setValidDateTo(new Date(ctrl.getValidDateTo()));
				}
				skuCtrl.setModifyUser(loginName);
				skuCtrl.setModifyTime(date);
		    	skuCtrlMapper.updateById(skuCtrl);
			}
			
			BeanUtil.copyNonNull(skuCtrl, ctrlResponse);
			response.setCtrl(ctrlResponse);
		}
    	
    	// 货品属性
		// 记录不删除的属性ID
		List<Integer> notDelIds = new ArrayList<Integer>();
		if (dto.getAttrs() != null) {
			SkuAttr skuAttr;
			List<SkuAttrResponse> attrs = new ArrayList<SkuAttrResponse>(dto.getAttrs().size());
			for (CreateUpdateSkuAttrRequest attr : dto.getAttrs()) {
				if (attr.getSkuAttrId() == null) {
					skuAttr = new SkuAttr();
					BeanUtil.copyNonNull(attr, skuAttr);
					skuAttr.setSkuId(sku.getSkuId());
					skuAttr.setCreateUser(loginName);
					skuAttr.setCreateTime(date);
					skuAttrMapper.insert(skuAttr);
				} else {
					skuAttr = skuAttrMapper.selectById(attr.getSkuAttrId());
					BeanUtil.copy(attr, skuAttr);
					skuAttr.setModifyUser(loginName);
					skuAttr.setModifyTime(date);
					skuAttrMapper.updateById(skuAttr);
				}
				notDelIds.add(skuAttr.getSkuAttrId());
				
				SkuAttrResponse skuAttrResponse = new SkuAttrResponse();
				BeanUtil.copyNonNull(skuAttr, skuAttrResponse);
				attrs.add(skuAttrResponse);
			}
			response.setAttrs(attrs);
		}
		
		// 删除属性
		QueryWrapper<SkuAttr> skuAttrWrapper = new QueryWrapper<>();
		skuAttrWrapper.eq("SKU_ID", dto.getSkuId());
		if (notDelIds.size() > 0) {
			skuAttrWrapper.notIn("SKU_ATTR_ID", notDelIds);
		}
		skuAttrMapper.delete(skuAttrWrapper);
		return response;
    }
	
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public <T> Result<T> updateStatus(UpdateStatusSkuRequest dto,
    		HttpServletRequest servletRequest) {
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	
    	Sku sku = new Sku();
    	sku.setSkuId(dto.getSkuId());
    	sku.setIsEnabled(dto.getIsEnabled());
    	sku.setModifyUser(loginName);
    	sku.setModifyTime(new Date());
    	skuMapper.updateById(sku);
		return new Result<>();
    }

	/**
	 *
	 * @param skuIdList
	 * @return
	 */
	public List<Sku> getSkuListBySkuIdList(List<Integer> skuIdList){

		//创建类型的条件构造器
		QueryWrapper<Sku> wrapper = new QueryWrapper<>();
		wrapper.in("SKU_ID",skuIdList);

		List<Sku> skuList = skuMapper.selectList(wrapper);
		return skuList;
	}

	/**
	 * 根据主键获取实体信息
	 * @param skuId
	 * @return
	 */
	public Sku getSkuByPk(Integer skuId) {
		Sku sku = skuMapper.selectById(skuId);
		return sku;
	}

	/**
	 * 查询物料代码搜索框信息
	 * @param skuCode
	 * @return
	 */
	public PagerInfo<List<SkuInputResponse>> getSkuInput(SearchSkuInputRequest dto, Pager<?> pager) {
		Page<SkuInputResponse> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
		List<SkuInputResponse> datas = skuMapper.selectSkuInput(dto);
		PagerInfo<List<SkuInputResponse>> pagerInfo = new PagerInfo<>();
		pagerInfo.setTotalCount(page.getTotal());
		pagerInfo.setItems(datas);
		return pagerInfo;
	}
}
